package com.uchiha.nova.core.dynamic;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.uchiha.nova.core.tool.util.AuthUtil;
import com.uchiha.nova.core.tool.util.StringUtil;
import lombok.Setter;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

/**
 * @author 周林静
 * @Date 2023-01-10,0010 14:25
 * @Version 1.0
 */
public class TenantDataSourceGlobalInterceptor implements MethodInterceptor {

    @Setter
    private TenantDataSourceHolder holder;

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        String tenantId = AuthUtil.getUser().getTenantId();
        try {
            if (StringUtil.isNotBlank(tenantId)) {
                holder.handleDataSource(tenantId);
                DynamicDataSourceContextHolder.push(tenantId);
            }
            return invocation.proceed();
        } catch (Exception exception) {
            throw new TenantDataSourceException(exception.getMessage());
        } finally {
            if (StringUtil.isNotBlank(tenantId)) {
                DynamicDataSourceContextHolder.poll();
            }
        }
    }
}
